package mobi.smarthosts;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;

public class DownloadHostsTask extends AsyncTask<Void, Integer, Hosts[]> {

    private Context mContext;
    private boolean mForeground;
    private Configuration mConf;
    private SharedPreferences mPref;
    private TaskHandler mHandler;

    public DownloadHostsTask() {}

    public DownloadHostsTask(Context context, boolean foreground) {
        mContext = context;
        mHandler = (TaskHandler) context;
        mForeground = foreground;
        mConf = Configuration.getInstance(context);
        mPref = PreferenceManager.getDefaultSharedPreferences(context);
    }

    @Override
    protected Hosts[] doInBackground(Void... params) {
        if (!mForeground && mPref.getBoolean(PrefKeys.KEY_CHECK_UPDATE, false));

        if (mForeground) {
            ViewHelper.showProgressDialog(mContext,
                    mContext.getString(R.string.msg_checkingUpdate));
        }

        try {
            Hosts[] result = new Hosts[1];

            // Download hosts from update site
            Log.d("Downloading hosts file from URL: %s", mConf.getUpdateSiteUrl(mContext));
            byte[] rawData = HttpHelper.simpleHttpRequest(mConf.getUpdateSiteUrl(mContext));
            result[0] = new Hosts(mContext.getString(R.string.app_name), new String(rawData));
            Log.d("Download hosts file successed with md5 %s, size %s", result[0].md5, rawData.length);

            return result;
        } catch (SmartHostsException e) {
            Log.e("Download hosts failed.", e);
            if (mForeground) {
                ViewHelper.dismissProgressDialog();
                ViewHelper.showAlertDialog(mContext,
                        mContext.getString(R.string.title_error),
                        mContext.getString(R.string.error_downloadFailed, e.getMessage()),
                        mContext.getString(R.string.label_cancel), null);
            }
            return null;
        }
    }

    @Override
    protected void onPostExecute(Hosts[] hostsArray) {
        ViewHelper.dismissProgressDialog();
        mHandler.onDownloadCompleted(hostsArray);
    }

    /**
     * Handle download content.
     * Only SmartHosts in this array for the moment
     */
    public interface TaskHandler {
        public void onDownloadCompleted(Hosts[] hostsArray);
    }

}
